import EventEmitter from "events";
import memDB from "./memDB.js";
import moment from "moment";
class TCP_Client extends EventEmitter {
    constructor(socket) {
        super();
        EventEmitter.call(this);
        this.socket = socket;
        this.isReceive = false;
        this.receiveBuffer = null;
        this.isRegister = false;
        this.isOnLine = false;
        this.sn = '';
        this.socket.on('data', (data) => {
            
            let recStr = data.toString('hex').toUpperCase();
            console.log('接收到数据：',recStr,recStr.length);
            if (recStr.length == 20) {
                if (this.checkHeartbeat(recStr) == false && this.sn == "") {
                    this.close();
                }
                return;
            }
            console.log(this.sn,'接收到数据', data.toString('hex').toUpperCase());
            //  else {
            //     if (data.length==10) {
            //  //   if (data[0] > 0x01 && data[1] > 0x16) {
            //         console.log('心跳粘包');
            //         recStr = recStr.substring(0, 20);
            //         if (this.checkHeartbeat(recStr) == false && this.sn == "") {
            //             this.close();
            //         }
            //         else {
            //             let newLen = data.length - 10;
            //             if (newLen > 0) {

            //             let newBuffer = Buffer.alloc(newLen);
            //             data.copy(newBuffer, 0, 10, newLen);
            //             this.receiveBuffer = newBuffer;
            //             this.isReceive = true;
            //             let device = memDB.getDevice(this.sn);
            //             if (device == null) {
            //                 return false;
            //             }
            //             device.last_activivty = moment();
            //             console.log('device.last_activivty', device.last_activivty.format('YYYY-MM-DD HH:mm:ss')   );
            //             return;
            //             }
            //             else{
            //                 return;
                        
            //             }
            //         }
            //     }
            // }
            if (this.sn != "") {
                this.isReceive = true;
                this.receiveBuffer = data;
                let device = memDB.getDevice(this.sn);
                if (device == null) {
                    return false;
                }
                device.last_activivty = moment();
                console.log(this.sn, 'device.last_activivty', device.last_activivty.format('YYYY-MM-DD HH:mm:ss')   );
            }
        })
        this.socket.on('close', () => {
            console.log('socket close');
            this.close();
        });
        this.socket.on('error', (err) => {
            console.log('socket error', err);
            this.close();
        });
    }

    checkHeartbeat(sn) {
        let device = memDB.getDevice(sn);
        if (device == null) {
            return false;
        }
        device.last_activivty = moment();
        memDB.setDevice(device);
        if (this.sn == "") {
            this.sn = sn;
            console.log('device onLine', this.sn);
            this.isRegister = true;
            this.isOnLine = true;
            this.emit('register', this);
        }
        else {
            device.last_activivty = moment();
        }
        return true;
    }

    async SendData(data) {
        if (this.isOnLine == false) {
            console.log('链路未注册或者已经断开');
            return null;
        }
        if (this.socket != null && this.socket.writable == true) {
            this.socket.write(data);
            console.log(this.sn,'发送数据', data.toString('hex'));
            this.receiveBuffer = null;
            this.isReceive = false;
            return await this.waitReceive();
        }
        else {
            return null;
        }
    }
    async waitReceive() {
        let i = 0;
        while (i < 100) {
            await this.sleep(100);
            if (this.isReceive == true) {

                //      console.log('waitReceive',this.receiveBuffer.length, this.receiveBuffer.toString('hex'));
                return this.receiveBuffer;
            }
            i++;
        }
        return null;
    }
    sleep(ms) {
        return new Promise(resolve => setTimeout(resolve, ms))
    }
    //关闭当前的socket连接并释放该对象
    close() {
        try {
            this.socket.end();
        }
        catch (e) {
            console.log(this.sn,'关闭socket连接失败', e);
        }
        finally {
            this.socket = null;
            console.log(this.sn,'release');
            this.emit( 'release', this);
        }
    }

}
export default TCP_Client;